package com.zm.servlet;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zm.jdbc.AccessDb;


@SuppressWarnings("serial")
public class UpdateInfoServlet extends HttpServlet {
	
    private AccessDb db=null;
    private PreparedStatement stat=null;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init(ServletConfig config) throws ServletException{
		// Put your code here
		ServletContext application=config.getServletContext();
		
		if(application.getAttribute("accessdb")==null){
		
			db=new AccessDb();
			application.setAttribute("accessdb", db);
		}else
			db=(AccessDb)application.getAttribute("accessdb");
		
		try {
			stat=db.getConnection().prepareStatement("update account set name=?,passwd=?,age=?,telnum=?,sex=? where name=?");
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}
	
	public void decode(String str){
		try {
			byte[] temp=str.getBytes("ISO-8859-1");
			str=new String(temp,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean hasNewName(String oldname,String newname ){
		if(oldname.equals(newname))
			return false;
		else{
			return db.hasName(newname);
	     }
		
		
		
	}
	
	public void service(HttpServletRequest request,HttpServletResponse response){
	    String parameter=request.getQueryString();
	    try {
			parameter=URLDecoder.decode(parameter,"utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String[] paramPairs=parameter.split("&");
	    
		String[] params=new String[6];
		
		for(int i=0;i<6;i++){
			
			String[] temp=paramPairs[i].split("=");
			params[i]=temp[1];
			System.out.println(params[i]);
		}
		
		if(hasNewName(params[0],params[1])){
			
		}
		
	    try {
			stat.setString(1,params[1]);
			stat.setString(2,params[2]);
			stat.setInt(3,Integer.parseInt(params[3]));
			stat.setString(4,params[4]);
			stat.setString(5,params[5]);
			stat.setString(6,params[0]);
			int result=stat.executeUpdate();
		    response.sendRedirect("../AccessDb.jsp");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	  }
}
	
	


